//
//  TNScrollLabel.swift
//  TNMeeting
//
//  Created by Name i on 2021/8/19.
//

import Foundation
import SnapKit


class NNScrollLabel: UIScrollView {
    private lazy var contentView: UIView = {
        let view = UIView()
        return view
    }()
    
    private lazy var contentLabel0: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()
    
    private lazy var contentLabel1: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        return label
    }()

    /// 滚动速度
    public var speed: CGFloat = 0.5
    /// 两个文本之间的内容
    public var contentSpace: CGFloat = 30.0
    
    public var textColor: UIColor? = UIColor.black {
        didSet {
            guard let color = textColor else { return }
            contentLabel0.textColor = color
            contentLabel1.textColor = color
        }
    }

    public var font: UIFont = UIFont.systemFont(ofSize: 12) {
        didSet {
            contentLabel0.font = font
            contentLabel1.font = font
        }
    }
    
    
    /// 文本，目前仅支持单个文本
    public var contentText: String? {
        didSet {
            contentLabel0.text = contentText
            contentLabel1.text = contentText
        }
    }
    
    private lazy var link: CADisplayLink = {
        let link = CADisplayLink(target: self, selector: #selector(contentScroll))
        return link
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }

    private func setupUI() {
        addSubview(contentView)
        contentView.addSubview(contentLabel0)
        contentView.addSubview(contentLabel1)
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }
        contentLabel0.snp.makeConstraints { make in
            make.top.bottom.left.equalToSuperview()
            make.width.greaterThanOrEqualTo(self)
        }
        contentLabel1.snp.makeConstraints { make in
            make.top.bottom.right.equalToSuperview()
            make.left.equalTo(contentLabel0.snp.right).offset(contentSpace)
            make.width.greaterThanOrEqualTo(self)
        }
    }
    
    @objc private func contentScroll() {
        contentOffset.x += speed
        // 当第二个Label临界显示的时候，重置偏移
        if contentOffset.x >= contentLabel1.frame.size.width + contentSpace {
            contentOffset.x = .zero
        }
    }
    
    public func startAnimation() {
        guard let text = contentText, !text.isEmpty else { return }
        link.add(to: .main, forMode: .common)
    }
    
    
    public func stopAnimation() {
        link.invalidate()
    }
    
}
